import * as vscode from 'vscode';
import { JsonFormatter } from './JsonFormatter';

export class JsonResultViewer {
    public static showJsonResult(jsonString: string, title: string): void {
        const panel = vscode.window.createWebviewPanel(
            'jsonResult',
            title,
            vscode.ViewColumn.Two,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );

        panel.webview.html = JsonResultViewer.getJsonWebviewContent(jsonString, title);
    }

    public static showTextResult(text: string, title: string): void {
        const panel = vscode.window.createWebviewPanel(
            'textResult',
            title,
            vscode.ViewColumn.Two,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );

        panel.webview.html = JsonResultViewer.getTextWebviewContent(text, title);
    }

    private static getJsonWebviewContent(jsonString: string, title: string): string {
        // 转义JSON字符串中的反引号
        const escapedJsonString = jsonString.replace(/`/g, '\\`');
        
        return `
            <!DOCTYPE html>
            <html lang="zh">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>${title}</title>
                ${JsonFormatter.getJsonStyles()}
                <style>
                    body {
                        padding: 20px;
                        background-color: var(--vscode-editor-background);
                        color: var(--vscode-editor-foreground);
                        font-family: var(--vscode-font-family);
                        margin: 0;
                        height: 100vh;
                        display: flex;
                        flex-direction: column;
                    }
                    .header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 15px 20px;
                        border-bottom: 1px solid var(--vscode-editorWidget-border);
                        background-color: var(--vscode-editor-background);
                        position: sticky;
                        top: 0;
                        z-index: 100;
                    }
                    .title-section h2 {
                        margin: 0;
                        font-size: 18px;
                        font-weight: 600;
                    }
                    .title-section .subtitle {
                        font-size: 12px;
                        color: var(--vscode-descriptionForeground);
                        margin-top: 2px;
                    }
                    .controls {
                        display: flex;
                        gap: 8px;
                        align-items: center;
                    }
                    .control-button {
                        padding: 6px 12px;
                        background-color: var(--vscode-button-background);
                        color: var(--vscode-button-foreground);
                        border: none;
                        cursor: pointer;
                        border-radius: 2px;
                        font-size: 12px;
                        transition: background-color 0.2s;
                    }
                    .control-button:hover {
                        background-color: var(--vscode-button-hoverBackground);
                    }
                    .control-button:active {
                        background-color: var(--vscode-button-hoverBackground);
                        opacity: 0.8;
                    }
                    .control-button.secondary {
                        background-color: var(--vscode-input-background);
                        color: var(--vscode-input-foreground);
                        border: 1px solid var(--vscode-input-border);
                    }
                    .control-button.secondary:hover {
                        background-color: var(--vscode-input-background);
                        border-color: var(--vscode-focusBorder);
                    }
                    .json-container {
                        flex: 1;
                        overflow-y: auto;
                        padding: 20px;
                        background-color: var(--vscode-editor-background);
                    }
                    .json-stats {
                        font-size: 11px;
                        color: var(--vscode-descriptionForeground);
                        margin-bottom: 10px;
                    }
                    .search-container {
                        margin-bottom: 15px;
                        display: flex;
                        gap: 8px;
                        align-items: center;
                    }
                    .search-input {
                        flex: 1;
                        padding: 6px 8px;
                        background-color: var(--vscode-input-background);
                        color: var(--vscode-input-foreground);
                        border: 1px solid var(--vscode-input-border);
                        border-radius: 2px;
                        font-size: 12px;
                    }
                    .search-input:focus {
                        outline: none;
                        border-color: var(--vscode-focusBorder);
                    }
                    .status-bar {
                        padding: 8px 20px;
                        background-color: var(--vscode-statusBar-background);
                        color: var(--vscode-statusBar-foreground);
                        font-size: 12px;
                        border-top: 1px solid var(--vscode-editorWidget-border);
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                    .json-path {
                        font-family: 'Consolas', 'Monaco', monospace;
                        color: var(--vscode-descriptionForeground);
                    }
                    .copy-feedback {
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        padding: 8px 16px;
                        background-color: var(--vscode-badge-background);
                        color: var(--vscode-badge-foreground);
                        border-radius: 4px;
                        font-size: 12px;
                        opacity: 0;
                        transition: opacity 0.3s;
                        pointer-events: none;
                        z-index: 1000;
                    }
                    .copy-feedback.show {
                        opacity: 1;
                    }
                </style>
            </head>
            <body>
                    <div class="header">
                        <div class="title-section">
                            <h2>${title}</h2>
                        </div>
                        <div class="controls">
                            <input type="text" class="search-input" placeholder="搜索JSON内容..." id="searchInput">
                            <button class="control-button" onclick="expandAllJson()">展开全部</button>
                            <button class="control-button" onclick="collapseAllJson()">折叠全部</button>
                            <button class="control-button secondary" onclick="copyJson()">复制</button>
                            <button class="control-button secondary" onclick="downloadJson()">下载</button>
                        </div>
                    </div>
                    
                    <div class="json-container">
                        <div id="jsonContent">
                            ${JsonFormatter.formatJsonToHtml(jsonString)}
                        </div>
                    </div>
                    
                    ${JsonFormatter.getJsonStyles()}
                    ${JsonFormatter.getJsonScripts()}
                    
                    <script>
                        try {
                            let originalJson = ${JSON.stringify(JSON.parse(jsonString), null, 2)};
                            
                            // 搜索功能
                            document.getElementById('searchInput').addEventListener('input', function(e) {
                                const searchTerm = e.target.value.toLowerCase();
                                if (!searchTerm) {
                                    document.querySelectorAll('.json-toggle').forEach(toggle => {
                                        toggle.style.display = 'inline';
                                    });
                                    return;
                                }
                                
                                // 高亮匹配的节点
                                const allNodes = document.querySelectorAll('.json-string, .json-number, .json-boolean, .json-key');
                                allNodes.forEach(node => {
                                    const text = node.textContent.toLowerCase();
                                    if (text.includes(searchTerm)) {
                                        node.style.backgroundColor = 'var(--vscode-editor-findMatchHighlightBackground)';
                                        // 展开父节点
                                        let parent = node.parentElement;
                                        while (parent) {
                                            const toggle = parent.querySelector('.json-toggle');
                                            if (toggle && toggle.classList.contains('json-toggle')) {
                                                const children = parent.querySelector('.json-children');
                                                if (children) {
                                                    children.style.display = 'block';
                                                    toggle.classList.add('expanded');
                                                }
                                            }
                                            parent = parent.parentElement;
                                        }
                                    } else {
                                        node.style.backgroundColor = '';
                                    }
                                });
                            });
                            
                            // 复制功能
                            function copyJson() {
                                try {
                                    const json = typeof originalJson === 'string' ? JSON.parse(originalJson) : originalJson;
                                    const formatted = JSON.stringify(json, null, 2);
                                    navigator.clipboard.writeText(formatted).then(() => {
                                        showFeedback('已复制到剪贴板');
                                    });
                                } catch (e) {
                                    showFeedback('复制失败: ' + e.message);
                                }
                            }
                            
                            // 下载功能
                            function downloadJson() {
                                try {
                                    const json = typeof originalJson === 'string' ? JSON.parse(originalJson) : originalJson;
                                    const formatted = JSON.stringify(json, null, 2);
                                    const blob = new Blob([formatted], { type: 'application/json' });
                                    const url = URL.createObjectURL(blob);
                                    const a = document.createElement('a');
                                    a.href = url;
                                    a.download = 'result.json';
                                    a.click();
                                    URL.revokeObjectURL(url);
                                    showFeedback('已下载JSON文件');
                                } catch (e) {
                                    showFeedback('下载失败: ' + e.message);
                                }
                            }
                            
                            // 显示反馈
                            function showFeedback(message) {
                                const feedback = document.createElement('div');
                                feedback.textContent = message;
                                feedback.style.cssText = 'position:fixed;top:20px;right:20px;padding:8px 16px;background:var(--vscode-badge-background);color:var(--vscode-badge-foreground);border-radius:4px;z-index:1000;opacity:0;transition:opacity 0.3s';
                                document.body.appendChild(feedback);
                                setTimeout(() => feedback.style.opacity = '1', 10);
                                setTimeout(() => {
                                    feedback.style.opacity = '0';
                                    setTimeout(() => feedback.remove(), 300);
                                }, 2000);
                            }
                        } catch (e) {
                            document.getElementById('jsonContent').innerHTML = '<div class="json-error">JSON解析错误: ' + e.message + '</div>';
                        }
                    </script>
            </body>
            </html>
        `;
    }

    private static getTextWebviewContent(text: string, title: string): string {
        return `
            <!DOCTYPE html>
            <html lang="zh">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>${title}</title>
                <style>
                    body {
                        padding: 20px;
                        background-color: var(--vscode-editor-background);
                        color: var(--vscode-editor-foreground);
                        font-family: 'Consolas', 'Monaco', monospace;
                        font-size: 13px;
                        line-height: 1.5;
                    }
                    .header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 15px 20px;
                        border-bottom: 1px solid var(--vscode-editorWidget-border);
                    }
                    .header h2 {
                        margin: 0;
                        font-size: 18px;
                    }
                    .controls {
                        display: flex;
                        gap: 8px;
                    }
                    .control-button {
                        padding: 6px 12px;
                        background-color: var(--vscode-button-background);
                        color: var(--vscode-button-foreground);
                        border: none;
                        cursor: pointer;
                        border-radius: 2px;
                        font-size: 12px;
                    }
                    .content {
                        white-space: pre-wrap;
                        word-wrap: break-word;
                        padding: 20px;
                        background-color: var(--vscode-input-background);
                        border: 1px solid var(--vscode-input-border);
                        border-radius: 3px;
                        max-height: 70vh;
                        overflow-y: auto;
                    }
                </style>
            </head>
            <body>
                <div class="header">
                    <h2>${title}</h2>
                    <div class="controls">
                        <button class="control-button" onclick="copyText()">复制</button>
                        <button class="control-button" onclick="downloadText()">下载</button>
                        <button class="control-button" onclick="closeWindow()">关闭</button>
                    </div>
                </div>
                <div class="content">${text}</div>
                
                <script>
                    function copyText() {
                        const text = ${JSON.stringify(text)};
                        navigator.clipboard.writeText(text).then(() => {
                            const feedback = document.createElement('div');
                            feedback.textContent = '已复制到剪贴板';
                            feedback.style.cssText = 'position:fixed;top:20px;right:20px;padding:8px 16px;background:var(--vscode-badge-background);color:var(--vscode-badge-foreground);border-radius:4px;z-index:1000';
                            document.body.appendChild(feedback);
                            setTimeout(() => feedback.remove(), 2000);
                        });
                    }
                    
                    function downloadText() {
                        const text = ${JSON.stringify(text)};
                        const blob = new Blob([text], { type: 'text/plain' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'result.txt';
                        a.click();
                        URL.revokeObjectURL(url);
                        
                        const feedback = document.createElement('div');
                        feedback.textContent = '已下载文本文件';
                        feedback.style.cssText = 'position:fixed;top:20px;right:20px;padding:8px 16px;background:var(--vscode-badge-background);color:var(--vscode-badge-foreground);border-radius:4px;z-index:1000';
                        document.body.appendChild(feedback);
                        setTimeout(() => feedback.remove(), 2000);
                    }
                    
                    function closeWindow() {
                        vscode.postMessage({ command: 'closeWindow' });
                    }
                </script>
            </body>
            </html>
        `;
    }
}
